"use client"

import { useState } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Search, Download, ChevronLeft, ChevronRight } from "lucide-react"
import StatusBadge from "@/components/status-badge"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"

interface QueryResult {
  id: string
  title: string
  timestamp: string
  user: string
  status: string
  details: string
}

const mockResults: QueryResult[] = [
  {
    id: "OT-2024-001",
    title: "110kV线路检修操作票",
    timestamp: "2024-01-15 09:30:00",
    user: "operator1",
    status: "已完成",
    details: "12个操作步骤，耗时2小时30分钟",
  },
  {
    id: "OT-2024-002",
    title: "变压器停电操作",
    timestamp: "2024-01-16 14:20:00",
    user: "operator2",
    status: "执行中",
    details: "8个操作步骤，当前进行到第3步",
  },
  {
    id: "OT-2024-003",
    title: "接地线安装操作",
    timestamp: "2024-01-17 11:45:00",
    user: "operator1",
    status: "已完成",
    details: "5个操作步骤，耗时1小时15分钟",
  },
]

export default function QueryPage() {
  const [dateFrom, setDateFrom] = useState("")
  const [dateTo, setDateTo] = useState("")
  const [ticketId, setTicketId] = useState("")
  const [results, setResults] = useState<QueryResult[]>([])
  const [isSearching, setIsSearching] = useState(false)
  
  // 分页状态
  const [currentPage, setCurrentPage] = useState(0)
  const [pageSize, setPageSize] = useState(10)
  
  const pageSizeOptions = [5, 10, 20, 50]

  const handleSearch = async () => {
    setIsSearching(true)
    // 模拟搜索延迟
    setTimeout(() => {
      const filteredResults = mockResults.filter((result) => {
        if (ticketId && !result.id.toLowerCase().includes(ticketId.toLowerCase())) return false
        return true
      })
      setResults(filteredResults)
      setCurrentPage(0) // 重置到第一页
      setIsSearching(false)
    }, 1000)
  }

  const exportResults = () => {
    // 导出功能
    alert("查询结果已导出")
  }

  const getStatusVariant = (status: string) => {
    if (status.includes("完成")) return "normal"
    if (status.includes("执行") || status.includes("进行")) return "primary"
    if (status.includes("警告") || status.includes("注意")) return "warning"
    if (status.includes("失败") || status.includes("错误")) return "error"
    return "default"
  }
  
  // 计算分页数据
  const pageCount = Math.ceil(results.length / pageSize)
  const paginatedResults = results.slice(
    currentPage * pageSize,
    (currentPage + 1) * pageSize
  )

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold tracking-tight mb-2">作业票历史查询</h1>
        <p className="text-muted-foreground">
          在这里查询、筛选和管理所有历史作业票。
        </p>
      </div>

      <Card className="card-shadow">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-xl font-bold">作业票历史查询</CardTitle>
          {results.length > 0 && (
            <Button 
              variant="outline" 
              onClick={exportResults} 
              size="sm" 
              className="rounded-lg"
            >
              <Download className="w-4 h-4 mr-2" />
              导出结果
            </Button>
          )}
        </CardHeader>
        <CardContent>
          {/* 查询条件 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div className="space-y-2">
              <Label htmlFor="ticket-id">操作票号</Label>
              <Input
                id="ticket-id"
                placeholder="如: OT-2024-001"
                value={ticketId}
                onChange={(e) => setTicketId(e.target.value)}
                className="rounded-lg"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="date-from">开始日期</Label>
              <Input
                id="date-from"
                type="date"
                value={dateFrom}
                onChange={(e) => setDateFrom(e.target.value)}
                className="rounded-lg"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="date-to">结束日期</Label>
              <Input 
                id="date-to" 
                type="date" 
                value={dateTo} 
                onChange={(e) => setDateTo(e.target.value)} 
                className="rounded-lg"
              />
            </div>
          </div>

          <div className="flex justify-end space-x-3 mb-8 border-b pb-6">
            <Button 
              variant="outline" 
              onClick={() => {
                setDateFrom("");
                setDateTo("");
                setTicketId("");
              }}
              className="rounded-lg"
            >
              重置
            </Button>
            <Button 
              onClick={handleSearch} 
              disabled={isSearching} 
              className="rounded-lg bg-primary hover:bg-primary/90"
            >
              <Search className="w-4 h-4 mr-2" />
              {isSearching ? "查询中..." : "开始查询"}
            </Button>
          </div>

          {/* 查询结果 */}
          {results.length === 0 ? (
            <div className="text-center py-12 text-muted-foreground">
              <Search className="w-12 h-12 mx-auto mb-4 text-muted" />
              <p>请设置查询条件并点击"开始查询"</p>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader className="table-header">
                    <TableRow>
                      <TableHead>操作票号</TableHead>
                      <TableHead>标题/描述</TableHead>
                      <TableHead>时间</TableHead>
                      <TableHead>操作人员</TableHead>
                      <TableHead>状态</TableHead>
                      <TableHead>详细信息</TableHead>
                      <TableHead>操作</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {paginatedResults.map((result, index) => (
                      <TableRow key={result.id} className={index % 2 === 0 ? "table-row" : "table-row-alt table-row"}>
                        <TableCell className="font-medium">{result.id}</TableCell>
                        <TableCell>{result.title}</TableCell>
                        <TableCell>{result.timestamp}</TableCell>
                        <TableCell>{result.user}</TableCell>
                        <TableCell>
                          <StatusBadge status={getStatusVariant(result.status) as any}>
                            {result.status}
                          </StatusBadge>
                        </TableCell>
                        <TableCell className="max-w-xs truncate">{result.details}</TableCell>
                        <TableCell>
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            className="text-primary hover:text-primary/90 hover:bg-primary/10"
                          >
                            查看详情
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
              
              {/* 分页控件 */}
              <div className="flex items-center justify-between space-x-2 py-4 mt-4">
                <div className="flex items-center space-x-2">
                  <p className="text-sm text-muted-foreground">
                    每页显示
                  </p>
                  <Select
                    value={`${pageSize}`}
                    onValueChange={(value) => {
                      setPageSize(Number(value))
                      setCurrentPage(0) // 重置到第一页
                    }}
                  >
                    <SelectTrigger className="h-8 w-[70px] rounded-lg">
                      <SelectValue placeholder={pageSize} />
                    </SelectTrigger>
                    <SelectContent side="top" className="rounded-lg">
                      {pageSizeOptions.map((size) => (
                        <SelectItem key={size} value={`${size}`}>
                          {size}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-sm text-muted-foreground">
                    条记录，共 {results.length} 条
                  </p>
                </div>
                
                <div className="flex items-center space-x-6 lg:space-x-8">
                  <div className="flex items-center space-x-2">
                    <p className="text-sm text-muted-foreground">
                      第 {currentPage + 1} 页，共 {pageCount || 1} 页
                    </p>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(prev => Math.max(0, prev - 1))}
                      disabled={currentPage === 0}
                      className="rounded-lg"
                    >
                      <ChevronLeft className="h-4 w-4 mr-1" />
                      上一页
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setCurrentPage(prev => Math.min(pageCount - 1, prev + 1))}
                      disabled={currentPage >= pageCount - 1}
                      className="rounded-lg"
                    >
                      下一页
                      <ChevronRight className="h-4 w-4 ml-1" />
                    </Button>
                  </div>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
